using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using Ardal.MSBuildShellExtension.DomainModel.API;
using Ardal.MSBuildShellExtension.Loggers.ErrorListLogger.Properties;

/*
 * Copyright (c) 2007-2008, Thomas Ardal (thomasardalatgmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Thomas Ardal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
namespace Ardal.MSBuildShellExtension.Loggers.ErrorListLogger
{
    public partial class ErrorListForm : Form
    {
        private readonly ImageList imageList;
        private bool formShown;
        private readonly PersistWindowState windowState;

        public ErrorListForm(MSBuildErrorListLogger m)
        {
            InitializeComponent();
            m.Error += OnError;
            m.Warning += OnWarning;
            //m.Message += OnMessage;
            m.BuildFinished += OnBuildFinished;

            //Resources
            imageList = new ImageList();
            imageList.ColorDepth = ColorDepth.Depth32Bit;
            imageList.Images.Add("Error", Resources.Symbols_Error_16x16);
            imageList.Images.Add("Warning", Resources.Symbols_Warning_16x16);
            imageList.Images.Add("Message", Resources.Symbols_Info_16x16);
            itemListView.SmallImageList = imageList;

            windowState = new PersistWindowState();
            windowState.Parent = this;
            windowState.RegistryPath = @"Software\Ardal\MSBuildShellExtension";
            m.pool.Release();
        }

        public void OnBuildFinished(bool succeeded)
        {
            if (succeeded & itemListView.Items.Count == 0)
            {
                CloseForm();
            }
        }
        private void CloseForm()
        {
            formShown = false;
            Close();
        }

        public void OnError(string buildFile, string message, string file, string line, string column)
        {
            noOfErrors++;
            Data d = new Data(DataClassification.Error, buildFile, message, file, line, column);
            lock (items)
            {
                items.Add(d);
            }
            if (formShown && errorButton.Checked)
            {
                AddItem(d, true);
            }
            UpdateTitle();
        }

        public void OnWarning(string buildFile, string message, string file, string line, string column)
        {
            noOfWarnings++;
            Data d = new Data(DataClassification.Warning, buildFile, message, file, line, column);
            lock (items)
            {
                items.Add(d);
            }
            if (formShown && warningButton.Checked)
            {
                AddItem(d, true);
            }
            UpdateTitle();
        }

        public void OnMessage(string message)
        {
            //noOfMessages++;
            //Data d = new Data(DataClassification.Message, message, "", "", "");
            //lock (items)
            //{
            //    items.Add(d);
            //}
            //if (formShown && messageButton.Checked)
            //{
            //    AddItem(d, true);
            //}
            //UpdateTitle();
        }
        private void UpdateTitle()
        {
            if (InvokeRequired)
            {
                Invoke((MethodInvoker)(UpdateTitle));
                return;
            }

            Text = string.Format("Error List - E:{0} W:{1}", noOfErrors, noOfWarnings);
        }

        private readonly IList<Data> items = new List<Data>();
        private int noOfErrors = 0;
        private int noOfWarnings = 0;
        //private int noOfMessages = 0;

        private void ErrorListForm_Shown(object sender, EventArgs e)
        {
            lock (items)
            {
                foreach (Data item in items)
                {
                    AddItem(item, false);
                }
                RefreshListView();
            }
            formShown = true;
        }

        private delegate void RefreshListViewDelegate();
        private void RefreshListView()
        {
            if (itemListView.InvokeRequired)
            {
                itemListView.Invoke(new RefreshListViewDelegate(itemListView.Refresh));
            }
            else
            {
                itemListView.Refresh();
            }
        }

        private void AddItem(Data data, bool refresh)
        {
            ListViewItem listViewItem = new ListViewItem(new string[] { "", data.description, data.file, data.line, data.column, data.buildFile }, data.image);
            itemListView.Items.Add(listViewItem);
            if (refresh)
            {
                Refresh();
            }
        }

        private void ErrorListForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            formShown = false;
        }

        private void errorButton_Click(object sender, EventArgs e)
        {
            UpdateItems();
        }

        private void UpdateItems()
        {
            lock (items)
            {
                itemListView.Items.Clear();
                foreach (Data data in items)
                {
                    switch (data.classification)
                    {
                        case DataClassification.Error:
                            if (errorButton.Checked) itemListView.Items.Add(new ListViewItem(new string[] { "", data.description, data.file, data.line, data.column, data.buildFile }, data.image));
                            break;
                        case DataClassification.Message:
                            if (messageButton.Checked) itemListView.Items.Add(new ListViewItem(new string[] { "", data.description, data.file, data.line, data.column, data.buildFile }, data.image));
                            break;
                        case DataClassification.Warning:
                            if (warningButton.Checked) itemListView.Items.Add(new ListViewItem(new string[] { "", data.description, data.file, data.line, data.column, data.buildFile }, data.image));
                            break;
                    }
                }
                RefreshListView();
            }
        }

        public bool ShowErrors
        {
            get { return errorButton.Checked; }
            set { errorButton.Checked = value; }
        }

        public bool ShowWarnings
        {
            get { return warningButton.Checked; }
            set { warningButton.Checked = value; }
        }

        private void warningButton_Click(object sender, EventArgs e)
        {
            UpdateItems();
        }

        private void messageButton_Click(object sender, EventArgs e)
        {
            UpdateItems();
        }

        private void ItemSelected(IEditor editor)
        {
            ListView.SelectedListViewItemCollection selectedItems = itemListView.SelectedItems;
            if (selectedItems.Count > 1)
            {
                throw new ApplicationException("Only one selection allowed. Please report this programming error at http://www.codeplex.com/msbuildshellex/WorkItem/List.aspx.");
            }
            if (selectedItems.Count == 1 && editor != null)
            {
                string filename = selectedItems[0].SubItems[2].Text;
                string line = selectedItems[0].SubItems[3].Text;
                string column = selectedItems[0].SubItems[4].Text;
                string buildFile = selectedItems[0].SubItems[5].Text;

                //Return if double clicked on item with no filename speified (could be messages)
                //Also return if build project has not been set.
                if (string.IsNullOrEmpty(filename))
                {
                    MessageBox.Show("Filename could not be resolved.");
                    return;
                }
                if (string.IsNullOrEmpty(buildFile))
                {
                    MessageBox.Show("Build project could not be resolved. This error is caused by a poorly created API for MSBuild tools like MSBuildShellExtension. Sorry :(");
                    return;
                }
                //Remove directories from filename (example: Properties\AssemblyInfo.cs -> AssemblyInfo.cs)
                string root = buildFile.Substring(0, buildFile.LastIndexOf("\\"));
                int index = filename.LastIndexOf("\\");
                if (index != -1)
                {
                    filename = filename.Substring(index + 1);
                }

                //Get full name of file (example: AssemblyInfo.cs -> c:\projects\test\properties\AssemblyInfo.cs)
                DirectoryInfo rootDirectory = new DirectoryInfo(root);
                FileInfo[] files = rootDirectory.GetFiles(filename, SearchOption.AllDirectories);
                if (files.Length == 0)
                {
                    MessageBox.Show(string.Format("Could not find absolute path to file {0}.", filename));
                    return;
                }

                string selectedEditorArguments = editor.Arguments;
                selectedEditorArguments = selectedEditorArguments.Replace(EditorVariableConstants.BuildFileVariable, buildFile);
                selectedEditorArguments = selectedEditorArguments.Replace(EditorVariableConstants.FileVariable, files[0].FullName);
                selectedEditorArguments = selectedEditorArguments.Replace(EditorVariableConstants.LineVariable, line);
                selectedEditorArguments = selectedEditorArguments.Replace(EditorVariableConstants.ColumnVariable, column);
                string selectedEditorFilename = editor.Filename;
                selectedEditorFilename = selectedEditorFilename.Replace(EditorVariableConstants.ProgramFilesVariable, Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles));
                ProcessStartInfo processStartInfo = new ProcessStartInfo(selectedEditorFilename, selectedEditorArguments);
                Process.Start(processStartInfo);
            }
            else
            {
                MessageBox.Show("Selecting multiple files, is not supported.");
            }
        }

        private void itemListView_DoubleClick(object sender, EventArgs e)
        {
            ItemSelected(DomainModelFacade.Instance.DefaultEditor);
        }

        private void itemListView_MouseUp(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (itemListView.SelectedItems.Count > 0)
                {
                    contextMenuStrip1.Show(itemListView, e.Location);
                }
            }
        }

        private void openWithToolStripMenuItem_DropDownOpening(object sender, EventArgs e)
        {
            openWithToolStripMenuItem.DropDownItems.Clear();
            //Sort the list in order to show the default editor first
            List<IEditor> editors = new List<IEditor>(DomainModelFacade.Instance.Editors);
            editors.Sort(new SortByDefaultEditorComparer());
            foreach (IEditor editor in editors)
            {
                ToolStripItem item = new ToolStripMenuItem(editor.Title);
                //If this is the default editor, change font to Bold
                if (editor.DefaultEditor)
                {
                    item.Font = new Font(item.Font, FontStyle.Bold);
                }
                item.Click += delegate(object clickSender, EventArgs clickArgs)
                    {
                        ToolStripMenuItem selectedItem = clickSender as ToolStripMenuItem;
                        if (selectedItem != null)
                        {
                            IEditor selectedEditor = DomainModelFacade.Instance.FindEditorByTitle(selectedItem.Text);
                            if (selectedEditor != null)
                            {
                                ItemSelected(selectedEditor);
                            }
                        }
                    };
                openWithToolStripMenuItem.DropDownItems.Add(item);
            }
        }
    }

    public enum DataClassification
    {
        Message,
        Warning,
        Error
    }

    public class Data
    {
        public Data(DataClassification classification, string buildFile, string description, string file, string line, string column)
        {
            this.classification = classification;
            this.buildFile = buildFile;
            this.description = description;
            this.file = file;
            this.line = line;
            this.column = column;
        }

        public string image
        {
            get
            {
                switch (classification)
                {
                    case DataClassification.Error:
                        return "Error";
                    case DataClassification.Warning:
                        return "Warning";
                    case DataClassification.Message:
                        return "Message";
                    default:
                        throw new ApplicationException("Unknown classification: " + classification);
                }
            }
        }

        public DataClassification classification;
        public string description;
        public string buildFile;
        public string file;
        public string line;
        public string column;
    }

}